package com.code.httpserver;

import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JHTTP {

    private static final Logger logger = Logger.getLogger(
            JHTTP.class.getCanonicalName());
    private static final int NUM_THREADS = 50;
    private static final String INDEX_FILE = "index.html";

    private final File rootDirectory;
    private final int port;

    public JHTTP(File rootDirectory, int port) throws IOException {

        if (!rootDirectory.isDirectory()) {
            throw new IOException(rootDirectory + "不存在文件路径");
        }
        this.rootDirectory = rootDirectory;
        this.port = port;
    }

    public void start() throws IOException {
        ExecutorService pool = Executors.newFixedThreadPool(NUM_THREADS);
        try (ServerSocket server = new ServerSocket(port)) {
            logger.info("端口 " + server.getLocalPort());
            logger.info("根路径: " + rootDirectory);

            while (true) {
                try {
                    Socket request = server.accept();
                    Runnable r = new RequestProcessor(rootDirectory, INDEX_FILE, request);
                    pool.submit(r);
                } catch (IOException ex) {
                    logger.log(Level.WARNING, "IOException", ex);
                }
            }
        }
    }

    public static void main(String[] args) {
        File docroot = new File("/Users/yangzhi/Downloads/WebServer");

        int port = 8101;
        try {
            JHTTP webServer = new JHTTP(docroot, port);
            webServer.start();
        } catch (IOException ex) {
            logger.log(Level.SEVERE, "启动失败 ", ex);
        }
        // 浏览器访问 http://127.0.0.1:8101/FileTest.txt
    }
}